using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Xml;
using System.Text;
using com.googlecode.jenkins.helpers;

namespace com.googlecode.jenkins
{
    public class JenkinsClient
    {

        HttpHelper client = new HttpHelper();
        String jenkinsBaseURL;

        public JenkinsClient(String hudsonBaseURL)
        {
            jenkinsBaseURL = hudsonBaseURL;
        }

        public void authenticate(String username, String password)
        {
            var parameters = new Dictionary<string, string>
         {
             {"j_username", username},
             {"j_password", password},
             {"Login", "login"}
         };
            var resp = HttpHelper.Post(jenkinsBaseURL + "/j_acegi_security_check", parameters);

            if (resp.StatusCode != HttpStatusCode.OK)
            {
                throw new Exception("");
            }
        }
        public bool isHudsonURL()
        {
            var resp = HttpHelper.Get(jenkinsBaseURL);
            if (resp.StatusCode != HttpStatusCode.OK)
            {
                throw new Exception("");
            }
            return resp.GetResponseHeader("X-Hudson").Length != 0;
        }

        public void createJob(String jobName, Stream configFile)
        {
            var resp = HttpHelper.Post(jenkinsBaseURL + "/createItem?name=" + jobName, configFile, "application/xml; charset=ISO-8859-1");
            if (resp.StatusCode != HttpStatusCode.OK)
            {
                throw new Exception("");
            }
        }

        public void updateJob(String jobName, Stream configFile)
        {
            var resp = HttpHelper.Post(jenkinsBaseURL + "/job/" + jobName + "/config.xml", configFile, "application/xml; charset=ISO-8859-1");
            if (resp.StatusCode != HttpStatusCode.OK)
            {
                throw new Exception("");
            }
        }

        public void deleteJob(String jobName)
        {
            var resp = HttpHelper.Post(jenkinsBaseURL + "/job/" + jobName + "/doDelete");
            if (resp.StatusCode != HttpStatusCode.OK)
            {
                throw new Exception("");
            }
        }

        public void enableJob(String jobName)
        {
            var resp = HttpHelper.Post(jenkinsBaseURL + "/job/" + jobName + "/enable");
            if (resp.StatusCode != HttpStatusCode.OK)
            {
                throw new Exception("");
            }
        }

        public void disableJob(String jobName)
        {

            var resp = HttpHelper.Post(jenkinsBaseURL + "/job/" + jobName + "/disable");
            if (resp.StatusCode != HttpStatusCode.OK)
            {
                throw new Exception("");
            }
        }

        public Stream readJob(String jobName)
        {
            var resp = HttpHelper.Get(jenkinsBaseURL + "/job/" + jobName + "/config.xml");
            if (resp.StatusCode != HttpStatusCode.OK)
            {
                throw new Exception("");
            }
            return resp.GetResponseStream();
        }

        public void launchBuild(String jobName)
        {
            var resp = HttpHelper.Get(jenkinsBaseURL + "/job/" + jobName + "/build");
            if (resp.StatusCode != HttpStatusCode.OK)
            {
                throw new Exception("");
            }
        }

        public DateTime lastSuccessfullBuild(String jobName)
        {
            var resp = HttpHelper.Get(jenkinsBaseURL + "/job/" + jobName + "/lastSuccessfulBuild/buildTimestamp?format=dd/MM/yyyy");
            if (resp.StatusCode != HttpStatusCode.OK)
            {
                throw new Exception("");
            }
            var stream = resp.GetResponseStream();
            var lastSuccesfulBuild = Encoding.ASCII.GetString(StreamHelper.ReadFully(stream));
            return DateTime.Parse(lastSuccesfulBuild);
        }

        public List<Job> ReadJobStatus()
        {
            var jobStatus = new List<Job>();
            var resp = HttpHelper.Get(jenkinsBaseURL + "/api/xml");
            if (resp.StatusCode != HttpStatusCode.OK)
            {
                throw new Exception("");
            }
            var xPathDoc = new XmlDocument();
            xPathDoc.Load(resp.GetResponseStream());
            var jobList = xPathDoc.SelectNodes("/hudson/job");

            foreach (XmlNode node in jobList)
            {
                var nodeName = node["name"];
                var nodeColor = node["color"];
                jobStatus.Add(new Job(nodeName.InnerText, Job.create(nodeColor.InnerText)));
            }
            return jobStatus;
        }


    }


}